<template>
	<view class="wrap bg-fff">
        <button class="shareBtn" type="default" open-type="share">
            <image class="joinImg top-20" src="https://image.srea.org.cn/xcx/adviser-join-top.gif" mode="widthFix"></image>
        </button>
        <view class="fontBold fon15 top-20">填写入驻信息</view>
        <u-form :model="model" :rules="rules" ref="uForm" :label-style="labelSty" label-width="160">
            <u-form-item :rightIconStyle="{color: '#888', fontSize: '32rpx'}" label="负责楼盘">
                <block v-if="currentHouse.title">
                    <view @click="toSearchHouse">{{currentHouse.title}}</view>
                </block>
                <block v-else>
                    <view class="col-grey" @click="toSearchHouse">请选择负责楼盘</view>
                </block>
            </u-form-item>

            <u-form-item label="姓名" prop="name">
                <u-input placeholder="请输入姓名" v-model="model.name" type="text"></u-input>
            </u-form-item>
            <u-form-item label="微信" prop="wx_id" :rightIconStyle="{color: '#888', fontSize: '32rpx'}" right-icon="weixin-fill">
                <u-input placeholder="请输入微信号" v-model="model.wx_id" type="text"></u-input>
            </u-form-item>
            <u-form-item label="手机号" :rightIconStyle="{color: '#888', fontSize: '32rpx'}" right-icon="phone" prop="phone">
                <u-input placeholder="客户可直接联系到您的手机号" v-model="model.phone" type="number"></u-input>
            </u-form-item>
            <u-form-item label="验证码" prop="code" :rightIconStyle="{color: '#888', fontSize: '32rpx'}">
                <u-input placeholder="请输入验证码" v-model="model.code" type="text"></u-input>
                <u-button slot="right" type="success" size="mini" @click="getCode">{{codeTips}}</u-button>
            </u-form-item>
            <u-form-item label="展示头像">
                <view class="userHead">
                    <view class="imgItem flex" @click="uploadImgBtn('avatar_url')">
                        <block v-if="model.avatar_url[0].url">
                            <image :src="model.avatar_url[0].url" mode="aspectFill"></image>
                        </block>
                        <block v-else>
                            <u-icon name="plus" color="#999999" size="35"></u-icon>
                        </block>
                    </view>
                </view>
            </u-form-item>
            <u-form-item label="微信二维码">
                <view class="userHead">
                    <view class="imgItem flex" @click="uploadImgBtn('wx_qrcode')">
                        <block v-if="model.wx_qrcode[0].url">
                            <image :src="model.wx_qrcode[0].url" mode="aspectFill"></image>
                        </block>
                        <block v-else>
                            <u-icon name="plus" color="#999999" size="35"></u-icon>
                        </block>
                    </view>
                </view>
            </u-form-item>
            <u-form-item label="名片/工牌">
                <view class="userHead">
                    <view class="imgItem flex" @click="uploadImgBtn('card_url')">
                        <block v-if="model.card_url[0].url">
                            <image :src="model.card_url[0].url" mode="aspectFill"></image>
                        </block>
                        <block v-else>
                            <u-icon name="plus" color="#999999" size="35"></u-icon>
                        </block>
                    </view>
                </view>
            </u-form-item>
        </u-form>
        <u-button :custom-style="customStyle" @click="submit">提交</u-button>
        <!-- <u-verification-code seconds="60" ref="uCode" @change="codeChange"></u-verification-code> -->

        <up-modal :show="showPrivacy" title="用户隐私保护提示" :showCloseBtn="false" :showConfirmButton="false" :closeOnClickOverlay="true" @close="showPrivacy = false" @confirm="showPrivacy = false">
            <privacy-authorize @close="closePrivacyModal"></privacy-authorize>
        </up-modal>
	</view>
</template>

<script>
import { mapState, mapActions } from 'pinia';
import { useIndexStore, useUserInfoStore, useConfigStore } from '@/store/index';
import { checkLogin, checkUserInfo, checkWXPrivacyAuthorize, checkUploadImageParam, checkUploadDistParam, uuid, getFileType, upload_image } from '@/common/common';
import { adviserFormData, adviserMsgSubmit, getVerificationCode } from '@/common/api';

export default {
	data() {
		return {
            customStyle: {
                backgroundColor: '#FAA000',
                color: '#ffffff',
                border: 'none',
                marginTop: '40rpx'
            },
            labelSty: {
                display: 'inline-block',
                textAlign: 'justify',
                textAlignLast: 'justify',
                fontSize: '26rpx',
                marginRight: '20rpx'
            },
            adviserId: '',
            currentHouse: {},
            setting: false,
			model: {
                wx_qrcode: [],
                avatar_url: [],
				name: '',
                wx_id: '',
				phone: '',
                code: '',
                product: '',
                card:''
			},
            codeTips: '',
			rules: {
				name: [
					{
						required: true,
						message: '请输入姓名',
						trigger: 'blur' ,
					},
					{
						min: 2,
						max: 5,
						message: '姓名长度在2到5个字符',
						trigger: ['change','blur'],
					},
					{
						validator: (rule, value, callback) => {
							return this.$u.test.chinese(value);
						},
						message: '姓名必须为中文',
						trigger: ['change','blur'],
					}
				],
                wx_id: [
                    {
                    	required: true,
                    	message: '请输入微信号',
                    	trigger: ['change','blur'],
                    }
                ],
                phone: [
                	{
                		required: true,
                		message: '请填写有效手机号，客户可直接联系到您',
                		trigger: ['change','blur'],
                	},
                	{
                		validator: (rule, value, callback) => {
                			return this.$u.test.mobile(value);
                		},
                		message: '手机号码不正确',
                		trigger: ['change','blur'],
                	}
                ],
                code: [{
                    required: true,
                    message: '请输入验证码',
                    trigger: ['change','blur'],
                },{
                    type: 'number',
                    message: '验证码只能为数字',
                    trigger: ['change','blur'],
                }]
			},
            showPrivacy: false
		};
	},
    onReady() {
    	this.$refs.uForm.setRules(this.rules);
    },
    onShow() {
        //判断是否有卡片信息
        if(!this.setting && JSON.stringify(this.adviserCardData) !== "{}") {
            this.setting = true;
            this.model = {...this.model, ...this.adviserCardData};
        }
        //判断是否选择楼盘
        if(JSON.stringify(this.adviserSelectHouse) !== "{}"){
            this.currentHouse = this.adviserSelectHouse;
            this.model.product = this.adviserSelectHouse.id;
        }
    },
	onLoad(options) {
        let that = this;
        let { adviserId } = options;
        if(adviserId){
            this.adviserId = adviserId;
        }
        uni.$check_and_login(function(){
            that.init();
        })
	},
	computed: {
        ...mapState(useIndexStore, ['uploadParam', 'uploadDistParam', 'nowCityCode', 'adviserCardData', 'adviserSelectHouse']),
        ...mapState(useUserInfoStore, ['userInfo']),
        ...mapState(useConfigStore, ['puid']),
	},
	
    //分享
    onShareAppMessage(res) {
    	return {
    		title: '邀您入驻顾问之家',
    		path: `/pages/my/adviser/adviser-join?cityCode=${this.model.city_code}`,
    	}
    },
	methods: {
        ...mapActions(useIndexStore, ['setAdviserCardData']),
        async init(info){
            await checkUploadImageParam('public');
            await checkUploadDistParam();
            if(this.adviserId) {
                let resData = await adviserFormData(this.adviserId);
                if(resData.status === 0) {
                    this.model = resData.detail;
                    this.currentHouse.id = resData.detail.product;
                    this.currentHouse.title = resData.detail.product_title;
                }else{
                    uni.$u.toast(resData.detail);
                }
            }
        },
        
        //跳转搜索楼盘
        toSearchHouse(){
            uni.navigateTo({
            	url: `/pages/my/adviser/search-houses?cityCode=${this.model.city_code}`
            })
        },

        //关闭隐私政策模态框
        closePrivacyModal() {
            this.showPrivacy = false;
        },

        //上传图片
        async uploadImgBtn(type){
        	const that = this;

            if(!checkLogin()) {
                uni.navigateTo({
                    url: '/pages/login/login'
                })
                return
            }
            if(!checkUserInfo()) {
                uni.navigateTo({
                    url: `/pages/login/user-info-form`
                })
                return
            }

            let privacyRes = await checkWXPrivacyAuthorize();
            if(privacyRes) {
                this.showPrivacy = true;
                return
            }
            
        	uni.chooseMedia({
        		count: 1, //默认9
                mediaType: ['image'],
        		success: (res) => {
        			let fileObj = {};
        			res.tempFiles.forEach(item => {
        				let name = `adviser/${that.userInfo.id}/${uuid()}${getFileType(item.tempFilePath)}`;
                        fileObj = {url: item.tempFilePath, key: name}
        			})
                    //如果是上传卡片,使用卡片的上传参数
                    upload_image(type=='card_url'?that.uploadDistParam:that.uploadParam['public'], fileObj.url, fileObj.key, function(res, key){
                        that.model[type] = [fileObj];
                        that.setAdviserCardData({...that.model});
                    });
        		}
        	})
        },

        // 获取验证码
        getCode() {
            //#ifdef MP-TOUTIAO
            if(!this.model.phone) {
                this.$u.toast('请填写手机号');
                return
            }
            //#endif
            const that = this;
            if(this.$refs.uCode.canGetCode) {
                uni.showLoading({
                    title: '正在获取验证码',
                    mask: true
                })
                getVerificationCode({
                    type: 'login',
                    phone: that.model.phone
                }).then(res => {
                    if(res.status == 0) {
                        uni.hideLoading();
                        this.$u.toast('验证码已发送');
                        this.$refs.uCode.start();
                    }else {
                        uni.hideLoading();
                        this.$u.toast(res.detail);
                    }
                })
            } else {
                this.$u.toast('倒计时结束后再发送');
            }
        },

        //修改验证码
        codeChange(text) {
            this.codeTips = text;
        },

        //提交
		submit() {
            if(!this.model.product) {
                uni.showToast({
                    icon: 'none',
                	title: '请选择楼盘',
                });
                return
            }
            if(this.model.avatar_url.length == 0) {
                uni.showToast({
                    icon: 'none',
                	title: '请上传证件头像'
                });
                return
            }
            if(this.model.wx_qrcode.length == 0) {
                uni.showToast({
                    icon: 'none',
                	title: '请上传微信二维码',
                });
                return
            }
            if(this.model.card_url.length == 0) {
                uni.showToast({
                    icon: 'none',
                	title: '请上传名片或工牌',
                });
                return
            }
            
            this.model.parent_id = this.puid;

			this.$refs.uForm.validate(valid => {
				if (valid) {
                    uni.showLoading({
                    	title: '数据提交中',
                    	mask: true
                    })
                    adviserMsgSubmit(this.model, this.adviserId?'put':'post', this.adviserId).then(res => {
                        if(res.status == 0) {
                            uni.hideLoading();
                            uni.navigateTo({
                            	url: `/pages/my/adviser/adviser-status?id=${res.detail}`
                            })
                        }else if(res.status == 2) {
                            uni.hideLoading();
                            uni.showModal({
                                title: '提示',
                                confirmText: '联系客服',
                                content: '此手机号已被申请过',
                                success: function (succ) {
                                    if (succ.confirm) {
                                        uni.previewImage({
                                            current: 0,
                                            urls: [res.detail]
                                        })
                                    }
                                }
                            });
                        }else{
                            uni.hideLoading();
                            uni.$u.toast(res.detail);
                        }
                    })
				}
			});
		}
	}
};
</script>

<style scoped lang="scss">
.wrap {
    min-height: 100vh;
	padding: 0rpx 30rpx 30rpx 30rpx;
    position: relative;
    line-height: 1;
    .shareBtn{
        width: 100%;
        flex-direction: column;
        background: none;
        padding: 0;
        margin: 0;
        line-height: 1;
        &::after{
            border: none;
        }
    }
    .joinImg{
        width: 100%;
    }
    .userHead{
        .imgItem{
        	width: 120rpx;
        	height: 120rpx;
        	border: 1rpx dashed #999999;
        	border-radius: 10rpx;
        	overflow: hidden;
        	position: relative;
        	text{
        		font-size: 70rpx;
        	}
        	image{
        		width: 100%;
        		height: 100%;
        	}
        }
    }
}
</style>
